defmodule IocpMonitor.Dumper.Worker do
  @moduledoc """
  实时数据存储工作进程定义模块
  """

  use GenServer

  alias IocpMonitor.Schemas.{IocpLog2}
  alias IocpMonitor.Repo

  def start_link(_) do
    GenServer.start_link(__MODULE__, nil)
  end

  @impl true
  def init(_) do
    GenServer.cast(self(), :work)
    {:ok, nil}
  end

  @impl true
  def handle_cast(:work, connection) do
    data = BlockingQueue.pop(BlockingQueue)
    insert_voltage!(data)
    insert_amperage!(data)
    GenServer.cast(self(), :work)
    {:noreply, connection}
  end

  defp insert_voltage!(data) do
    id = UUID.uuid1() |> String.replace(~r/-/, "", global: true)

    struct = %IocpLog2{
      id: id,
      time: data.observed_at,
      facilityid: data.device_address |> Integer.to_string(),
      val: data.voltage / 10,
      type: "2"
    }
    Repo.insert!(struct)
  end

  defp insert_amperage!(data) do
    id = UUID.uuid1() |> String.replace(~r/-/, "", global: true)

    struct = %IocpLog2{
      id: id,
      time: data.observed_at,
      facilityid: data.device_address |> Integer.to_string(),
      val: data.amperage / 1000,
      type: "1"
    }
    Repo.insert!(struct)
  end
end
